import { prisma } from '../../utils/prisma'
import { signJwt } from '../../utils/auth'
import { z } from 'zod'

const bodySchema = z.object({
  lastDigits: z.string().length(4).regex(/^\d{4}$/)
})

export default eventHandler(async (event) => {
  const body = await readBody(event)
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const { lastDigits } = parsed.data
  const user = await prisma.user.findFirst({ where: { phone: { endsWith: lastDigits } }, orderBy: { id: 'asc' } })
  if (!user) throw createError({ statusCode: 401, statusMessage: 'UNAUTHORIZED' })
  const token = signJwt(user.id)
  setCookie(event, 'auth_token', token, {
    httpOnly: true,
    sameSite: 'lax',
    secure: false,
    path: '/',
  })
  return { ok: true }
})


